import 'package:flutter_enjoy_plus/constants/index.dart';
import 'package:shared_preferences/shared_preferences.dart';

class _TokenManager {
  // token
  String _token = '';
  // refresh
  String _refreshToken = '';
  // 初始化TOKEN示例
  _getInstance() {
    return SharedPreferences.getInstance();
    
  }

  // 初始化TOKEN
  Future<void> initToken() async {
    final prefs = await _getInstance();
    _token = prefs.getString(GlobalVariable.TOKEN) ?? '';
    _refreshToken = prefs.getString(GlobalVariable.REFRESH_TOKEN) ?? '';
  }

  // 存储TOKEN
  Future<void> setToken(String value, [String? refreshToken]) async {
    final prefs = await _getInstance();
    await prefs.setString(GlobalVariable.TOKEN, value);
    _token = value;
    if (refreshToken != null) {
      await prefs.setString(GlobalVariable.REFRESH_TOKEN, refreshToken);
      _refreshToken = refreshToken;
    }
  }

  // // 获取TOKEN
  // Future<String> getToken() async {
  //   final prefs = await _getInstance();
  //   return prefs.getString(GlobalVariable.TOKEN) ?? '';
  // }

  // 获取TOKEN
  getToken() {
    return _token;
  }

  // 获取REFRESH_TOKEN
  getRefreshToken() {
    return _refreshToken;
  }

  // 删除TOKEN
  Future<void> removeToken() async {
    final prefs = await _getInstance();
    await prefs.remove(GlobalVariable.TOKEN);
    await prefs.remove(GlobalVariable.REFRESH_TOKEN);
    _token = '';
    _refreshToken = '';
  }
}

// 单例模式
final tokenManager = _TokenManager();
